package com.yuan.util.number;

/**
 * @author YouYuan
 * @version 1.0
 * @CreateDate 2018/4/23 17:19
 * @UpdateDate 2018/4/23 17:19
 */
public class MathUtil {

    /**
     * 安全加法运算，防止数据溢出，若溢出将会抛出异常，更建议使用BigInteger
     * @param a
     * @param b
     * @return
     * @throws Exception
     */
    public static int safeAdd(int a, int b) throws Exception {
        int c = a + b;
        if (c < a) {
            throw new Exception("safeAdd 运算溢出 a:" + a + ", b:" + b);
        }
        return c;
    }

    /**
     * 安全减法运算，防止数据溢出，若溢出将会抛出异常，更建议使用BigInteger
     * @param a
     * @param b
     * @return
     * @throws Exception
     */
    public static int safeSub(int a, int b) throws Exception {
        int c = a - b;
        if (c > a) {
            throw new Exception("safeSub 运算溢出 a:" + a + ", b:" + b);
        }
        return c;
    }
}
